import json
import re
import time
from email.utils import parsedate_to_datetime

import pytz
import requests
from lxml import etree

from utils.dangdangEnum import kb_list, bz_list, yz_list
from utils.tools import compare_labels, compare_labels_pro, parse_number, get_file_content

import urllib.parse


def getTextXpathById(et, id):
    return et.xpath(f'//*[@id="{id}"]')[0].get('value')


# 通过isbn获取出版社信息
def get_publish_info_by_isbn(isbn, session_id):
    cookies = {
        'VRM_SID': session_id,
    }
    headers = {}
    params = {
        'SPBH': isbn,
        '_': str(time.time() * 1000),
    }
    response = requests.get('https://gyspt.dangdang.com/XPFB/GetBBandCBS/', params=params, cookies=cookies,
                            headers=headers)
    # 这里没有写重复！！！就是需要解析两次才能变成有用的json数据
    response_json = json.loads(response.text)
    response_json = json.loads(response_json)
    return response_json


# 通过父级分类获取子级分类默认图书一级分类为1805
# lx 分类ID 例如：获取二级分类 YXFLID2、 获取三级分类 YXFLID3
# cgw 父级分类ID
# 也可以用来获取开本数据案例写死 res = get_second_classify_by_first_classify('xxx', 'KBID', '')
# 也可以用来获取装帧数据案例写死 res = get_second_classify_by_first_classify('xxx', 'ZZID', '')
def get_second_classify_by_first_classify(session_id, lx, cgw):
    cookies = {
        'VRM_SID': session_id,
    }
    headers = {}
    params = {
        'lx': lx,
        'queryWhere': '',
        'cGLwhere': cgw,
        'pageIndexCZ': '1',
        'pageSizeCZ': '999999',
        '_': str(time.time() * 1000),
    }

    response = requests.get('https://gyspt.dangdang.com/XPFB/GetCZlist/', params=params, cookies=cookies,
                            headers=headers)

    response_json = json.loads(response.text)
    matches = re.findall(r'chooseCZ\((.*?)\)', response_json['data'])
    kinds_arr = []
    for match in matches:
        match = match.strip("'")  # 去掉外侧的单引号
        parts = match.split(",")  # 以逗号为分隔符分割字符串
        obj = {
            'label': parts[0].strip("'"),  # 去掉第一部分中的单引号
            'value': parts[1].strip("'"),  # 去掉第二部分中的单引号
        }
        kinds_arr.append(obj)

    return kinds_arr  # [{'label': '青春文学', 'value': '11559'}]


# def format_last_modified(last_modified_str):
#     # 解析Last-Modified字符串为datetime对象
#     dt_gmt = parsedate_to_datetime(last_modified_str)
#
#     # 将GMT时间转换到中国标准时间
#     china_tz = pytz.timezone('Asia/Shanghai')
#     dt_cst = dt_gmt.astimezone(china_tz)
#
#     # 格式化datetime对象为特定格式字符串
#     formatted_date_str = dt_cst.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (中国标准时间)')
#     return formatted_date_str
#
#
# def get_file_content(image_url):
#     res = requests.get(image_url)
#     file_name = image_url.split('/')[-1]
#     last_modified_str = res.headers['last-modified']
#     type = res.headers['content-type']
#     if last_modified_str:
#         last_modified_str = format_last_modified(last_modified_str)
#     else:
#         last_modified_str = 'Fri Jan 26 2024 09:06:16 GMT+0800 (中国标准时间)'
#     size = res.headers['content-length']
#     if size:
#         size = str(size)
#     else:
#         size = '9999'
#     # 检查请求是否成功
#     if res.status_code == 200:
#         return {'content': res.content, 'size': size,
#                 'lastModifiedDate': last_modified_str, 'file_name': file_name, 'type': type}
#     else:
#         return None


# 注意哦，目前来说这个接口没有做任何校验哦
def uploadCipPicture(url):
    print('CipPicture' + url)
    result = get_file_content(url)
    files = {
        'uploadType': (None, 'bookUploadCIPImg'),
        'copyright_img': (result['file_name'], result['content'], result['type']),
    }
    response = requests.post(
        'https://vrmpimsup.dangdang.com/vrmpimsup/ItemUploadImg/uploadCIPImg',
        files=files,
    )
    response_json = json.loads(response.text)
    print(response_json)
    if 'filePath' in response_json and response_json['filePath'] is not None:
        print(response_json['filePath'])
        return {'code': 200, 'data': response_json['filePath']}
    else:
        return {'code': 0, 'message': '操作失败', 'reason': response_json}


def uploadMainPicture(url):
    print('mainPicture' + url)
    result = get_file_content(url)
    files = {
        'uploadType': (None, 'bookUploadImg'),
        'isMainPic': (None, 'isMainPic'),
        'uploadFile': (result['file_name'], result['content'], result['type']),
    }
    response = requests.post(
        'https://vrmpimsup.dangdang.com/vrmpimsup/ItemUploadImg/multiUploadImg',
        files=files,
    )
    response_json = json.loads(response.text)
    print(response_json)
    if 'filePath' in response_json and response_json['filePath'] is not None:
        print(response_json['filePath'])
        return {'code': 200, 'data': response_json['filePath']}
    else:
        return {'code': 0, 'message': '操作失败', 'reason': response_json}


def submitBase(book_details_json, session_id, YXFLID2, YXFLID3, discount, SJSL):
    gp_json = get_publish_info_by_isbn(book_details_json['isbn'], session_id)
    bb_id = gp_json['BBID']
    cbs_id = gp_json['CBSID']
    kb_id = ''
    kb_arr = get_second_classify_by_first_classify(session_id, 'KBID', '')
    zz_id = ''
    zz_arr = get_second_classify_by_first_classify(session_id, 'ZZID', '')
    if compare_labels(book_details_json['bookSize'], kb_arr) is not None:
        kb_id = compare_labels(book_details_json['bookSize'], zz_arr)
    if compare_labels(book_details_json['binding'], kb_arr) is not None:
        zz_id = compare_labels(book_details_json['binding'], zz_arr)
    data = {
        'SPXXID': '',
        'SPZLID': '1',  # 商品种类ID 默认值-图书
        'SPJZID': '0',  # 商品介质ID 默认值-图书
        'SL': '0',  # 税率 默认值-0 必填
        'SPBH': book_details_json['isbn'] or '',  # ISBN 必填
        'TXM': book_details_json['isbn'] or '',  # 应该是条形码的意思，暂时发现值和ISBN一样 必填
        'BBID': bb_id,  # 报版单位ID 通过ISBN获取 必填
        'CBSID': cbs_id,  # 出版社ID 通过ISBN获取 必填
        'DJ': book_details_json['priceFixed'] or '',  # 定价 必填
        'PM': book_details_json['bookName'] or '',  # 品名 必填
        'JZ': discount,  # 首次进折 必填
        'SJSL': SJSL,  # 建议首进数量 必填
        'YXFLID1': '1805',  # 一级分类 默认值 1805 图书 必填
        'YXFLID2': YXFLID2,  # 二级分类 必填
        'YXFLID3': YXFLID3,  # 三级分类 必填
        'YXFLID4': '',  # 四级分类
        'YXFLID5': '',  # 五级分类
        'zuozhe': book_details_json['authorName'] or '',  # 作者 必填
        'CBNY': book_details_json['publishDate'] or '',  # 出版年月
        'BC': book_details_json['versionNo'] or '',  # 版次
        'YC': book_details_json['printNo'] or '',  # 印次
        'YSSJ': '',  # 印刷年月
        'KBID': kb_id,  # 开本ID
        'ZZID': zz_id,  # 装帧ID
        'CD': book_details_json['bookInfoAppendObj']['lengthBook'] or '',  # 长度
        'KD': book_details_json['bookInfoAppendObj']['widthBook'] or '',  # 宽度
        'GD': book_details_json['bookInfoAppendObj']['depthBook'] or '',  # 高度
        'MBZL': book_details_json['bookInfoAppendObj']['weight'] or '',  # 单个重量
        'MBTS': '',  # 自然包数
        'MTCS': '',  # 每包册数
        'GYSSPID': '',  # 供应商商品信息ID
        'CIP': book_details_json['bookInfoAppendObj']['classificationNumber'] or '',  # CIP分类
    }
    publish_base_response = requests.post('https://gyspt.dangdang.com/XPFB/AddAndEdit_TS_YX_BH_QK/', cookies={
        'VRM_SID': session_id,
    }, headers={}, data=data)
    if publish_base_response.text == True or publish_base_response.text == 'True':
        return {'code': 200, 'message': '发布成功!'}


def submitSecond(book_details_json, session_id, productId):
    cookies = {
        'VRM_SID': session_id,
    }
    page_params = {
        'productId': productId,
    }
    page_response = requests.get(
        'https://vrmpimsup.dangdang.com/vrmpimsup/itembook/showModify',
        params=page_params,
        cookies=cookies,
    )
    # 图片
    # 版权页
    book_info_file_obj_list = book_details_json['bookInfoFileObjList']
    banquan_dcc_url = next((item for item in book_info_file_obj_list if item["fileType"] == "4"), None)
    if not banquan_dcc_url:
        return {'code': 0, 'message': '请传入版权图'}
    # 条码图
    barcode_dcc_url = next((item for item in book_info_file_obj_list if item["fileType"] == "6"), None)
    if not barcode_dcc_url:
        return {'code': 0, 'message': '请传入条码图'}
    # 上传主图
    # zhutu_dcc_url = next((item for item in book_info_file_obj_list if item["fileType"] == "1"), None)
    # if not zhutu_dcc_url:
    #     return {'code': 0, 'message': '请传入主图'}
    ltf_dcc_urls = [item for item in book_info_file_obj_list if item["fileType"] == "1"]
    if not ltf_dcc_urls:
        return {'code': 0, 'message': '请传入主图'}
    banquan_url = uploadCipPicture(banquan_dcc_url['webUrl'])
    if 'data' in banquan_url:
        banquan_url = banquan_url['data']
    else:
        return banquan_url
    barcode_url = uploadCipPicture(barcode_dcc_url['webUrl'])
    if 'data' in barcode_url:
        barcode_url = barcode_url['data']
    else:
        return barcode_url
    zhutu_url = []
    for item in ltf_dcc_urls:
        resData = uploadMainPicture(item['webUrl'])
        if 'data' in resData:
            zhutu_url.append(resData['data'])
        else:
            return resData
    # zhutu_url = uploadMainPicture(zhutu_dcc_url['webUrl'])
    # if 'data' in zhutu_url:
    #     zhutu_url = zhutu_url['data']
    # else:
    #     return [zhutu_url]
    kbs = compare_labels_pro(book_details_json['authorName'], kb_list)
    zzs = compare_labels_pro(book_details_json['binding'], bz_list)
    word_number = parse_number(book_details_json['fontNumber'])
    if word_number != '':
        word_number = str(int(word_number) / 1000)
    et = etree.HTML(page_response.text)
    itemId = getTextXpathById(et, 'item_id')  # 商品编号
    outItemId = ''  # 暂时没找到在哪，页面上也没有，就默认为空吧
    itemName = getTextXpathById(et, 'item_name')  # 商品名称
    isbn = getTextXpathById(et, 'isbn')  # isbn
    publisher = getTextXpathById(et, 'publisher')  # 出版社
    # 出版社Id暂时没有找到在哪传的值，有可能没传
    # 媒质也是，没有这个数据，没找到这个字段
    marketPrice = getTextXpathById(et, 'price')  # 定价
    mainBookName = book_details_json['cipBookName']  # CIP书名 必填
    itemNameSub = ''  # 副标题
    authorName = book_details_json['authorName'] or ''  # 作者  必填
    publishDate = book_details_json['publishDate'] or ''  # 出版时间  必填
    isSuit = '0'  # 是否套装 -- 默认0，必填
    sizeId = kbs['value']  # 开本，传的是id 必填
    size = kbs['label']  # 开本文本 必填
    version = book_details_json['versionNo'] or ''  # 版次 必填
    printCopy = book_details_json['printNo']  # 印次 必填
    printDate = book_details_json['publishDate'] or ''  # 印刷时间 必填 暂时和印刷时间填一个吧
    paperQuality = compare_labels(book_details_json['userPaper'], yz_list) or '胶版纸'  # 用纸文本 必填
    binding = zzs['label']  # 包装文本
    bindingId = zzs['value']  # 包装id
    pages = parse_number(book_details_json['pagesNumber']) or ''  # 页数
    printPaper = book_details_json['printPage'] or ''  # 印张
    wordNum = word_number  # 字数
    copiesNumber = ''  # 册数
    language = '中文（简体）'  # 正文语种文本 默认 中文（简体）
    isPinyin = '0'  # 是否注音 默认否、 否 0 是1
    edition = ''  # 版本文本 默认影印本
    cblCategory = book_details_json['bookInfoAppendObj']['classificationNumber'] or ''  # 中图法分类号
    presentId = '0'  # 附赠默认id 无-0
    present = '无'  # 附赠文本 默认 无
    presentNum = ''  # 附赠数量，有则必填
    modelAttrStr = ''  # 作者国别/地区/朝代ID: value; 原版书名: value; 例如：1000496:宋朝;1000619:原版书名;
    commonAttrStr = ''  # 1000732:1_7_19;1000714:1; 选多个用下划线隔开
    volumeName = ''  # 分册名 --必填
    volumeNumber = ''  # 分册号
    reignTitle = ''  # 年号
    # 前面的版本填过了，不用再填了
    cipNumber = ''  # cip数据编号 案例，冒号隔开: 1111:222222
    editor = book_details_json['editorResponsible'] or ''  # 编者
    translator = book_details_json['translatorName'] or ''  # 译者
    painter = ''  # 绘者
    publishingBrands = ''  # 出版品牌
    barcodeImg = barcode_url  # 条码图片url完整地址
    productsCopyrightImage = banquan_url  # 版权页图片url完整地址

    imageUrlList = zhutu_url  # 主图 至少一张 800X800 -- 必填
    marketingImgUrl = ''  # 营销素材图 800X800 先不传
    # videoInfo = [{"type": 1, "mediaUrl": "", "mediaName": "", "mediaFileid": "", "coverImage": ""},
    #              {"type": 2, "mediaUrl": "", "mediaName": "", "mediaFileid": "", "coverImage": ""}]  # 视频也先不传
    videoInfo = ''
    # 产品详情不能为空 -每一个产品详情最外层都要加一个p标签哦
    itemFeatures = ''  # 产品特色(产品详情)
    editRecommend = ''  # 编辑推荐(产品详情)
    contentRecommend = ''  # 内容简介(产品详情)
    authorItro = ''  # 作者简介(产品详情)
    mediaComment = ''  # 媒体评论(产品详情)
    catelog = ''  # 目录(产品详情)
    preface = ''  # 前言(产品详情)
    wonderfulDigest = ''  # 免费在线读(产品详情)
    illustration = ''  # 书摘与插画(产品详情)
    itemMobileDetail = ''  # 手机端描述(产品详情) 是根据产品详情拼接而来 例如 【作者简介】<br><p>作者简介</p><br>【媒体评论】<br><p>媒体评论</p><br>
    app_str1 = book_details_json["bookInfoAdditionObj"]["editRecommend"].replace('\n', '<br>')
    app_str2 = book_details_json["bookInfoAdditionObj"]["briefIntroduction"].replace('\n', '<br>')
    app_str3 = book_details_json["bookInfoAdditionObj"]["authorAbout"].replace('\n', '<br>')
    app_str4 = book_details_json["bookInfoAdditionObj"]["mediaReview"].replace('\n', '<br>')
    app_str5 = book_details_json["bookInfoAdditionObj"]["tableOfContents"].replace('\n', '<br>')
    app_str6 = book_details_json["bookInfoAdditionObj"]["preface"].replace('\n', '<br>')
    app_str7 = book_details_json["bookInfoAdditionObj"]["onlineReading"].replace('\n', '<br>')
    if book_details_json.get("bookInfoAdditionObj", {}).get("editRecommend"):
        editRecommend = f'<p>{app_str1}</p>'
        itemMobileDetail += f'【编辑推荐】<br><p>{app_str1}</p><br>'
    if book_details_json.get("bookInfoAdditionObj", {}).get("briefIntroduction"):
        contentRecommend = f'<p>{app_str2}</p>'
        itemMobileDetail += f'【内容简介】<br><p>{app_str2}</p><br>'
    if book_details_json.get("bookInfoAdditionObj", {}).get("authorAbout"):
        authorItro = f'<p>{app_str3}</p>'
        itemMobileDetail += f'【作者简介】<br><p>{app_str3}</p><br>'
    if book_details_json.get("bookInfoAdditionObj", {}).get("mediaReview"):
        mediaComment = f'<p>{app_str4}</p>'
        itemMobileDetail += f'【媒体评论】<br><p>{app_str4}</p><br>'
    if book_details_json.get("bookInfoAdditionObj", {}).get("tableOfContents"):
        catelog = f'<p>{app_str5}</p>'
        itemMobileDetail += f'【目录】<br><p>{app_str5}</p><br>'
    if book_details_json.get("bookInfoAdditionObj", {}).get("preface"):
        preface = f'<p>{app_str6}</p>'
        itemMobileDetail += f'【前言】<br><p>{app_str6}</p><br>'
    if book_details_json.get("bookInfoAdditionObj", {}).get("onlineReading"):
        wonderfulDigest = f'<p>{app_str7}</p>'
        itemMobileDetail += f'【免费在线读】<br><p>{app_str7}</p><br>'
    editRecommendIndex = ''  # 编辑推荐索引默认传
    contentRecommendIndex = ''  # 内容简介索引默认传
    authorItroIndex = ''  # 作者简介索引默认传
    mediaCommentIndex = ''  # 媒体评论索引默认传
    catelogIndex = ''  # 目录推荐索引默认传
    prefaceIndex = ''  # 前言索引默认传
    wonderfulDigestIndex = ''  # 免费在线读索引默认传
    illustrationIndex = ''  # 书摘与插画索引默认传
    readChapter = ''  # 抢先读
    # 下边的都不知道是什么
    itemCategoryId = ''
    itemSubcategoryId1 = ''
    itemSubcategoryId2 = ''
    originalBookName = ''
    salePrice = ''
    stockPrice = ''
    isShopVip = ''
    status = ''
    isCod = ''
    columnDescListId = ''
    columnSortNum = ''
    seriesName = ''
    params = {
        # --- disabled 基础信息
        'itemId': itemId,  # 商品编号
        'outItemId': outItemId,  # 暂时没找到在哪，页面上也没有，就默认为空吧
        'itemName': urllib.parse.quote(itemName),  # 商品名称
        'isbn': urllib.parse.quote(isbn),  # isbn
        'publisher': urllib.parse.quote(publisher),  # 出版社
        # 出版社Id暂时没有找到在哪传的值，有可能没传
        # 媒质也是，没有这个数据，没找到这个字段
        'marketPrice': urllib.parse.quote(marketPrice),  # 定价
        # --------- end
        'mainBookName': urllib.parse.quote(mainBookName) if mainBookName else '',  # CIP书名 -- 必填
        'itemNameSub': urllib.parse.quote(itemNameSub),  # 副标题
        'authorName': urllib.parse.quote(authorName),  # 作者 （输入作者、编者、译者、绘者，姓名和著、编、译、绘之间用一个空格隔开，不同角色间用逗号隔开）-- 必填
        'publishDate': publishDate,  # 出版时间 -- 必填
        'isSuit': isSuit,  # 是否套装 -- 默认0否，是传1，必填
        'sizeId': sizeId,  # 开本id -- 必填
        'size': urllib.parse.quote(size),  # 开本文本 -- 必填
        'version': version,  # 版次 -- 必填
        'printCopy': printCopy,  # 印次 -- 必填
        'printDate': printDate,  # 印刷时间 -- 必填
        'paperQuality': urllib.parse.quote(paperQuality),  # 用纸文本 -- 必填
        'binding': urllib.parse.quote(binding),  # 包装文本 -- 必填
        'bindingId': bindingId,  # 包装id -- 必填
        'pages': pages,  # 页数
        'printPaper': urllib.parse.quote(printPaper),  # 印张
        'wordNum': wordNum,  # 字数
        'copiesNumber': copiesNumber,  # 册数
        'language': urllib.parse.quote(language),  # 正文语种文本
        'isPinyin': isPinyin,  # 是否注音 默认否、 否 0 是1
        'edition': urllib.parse.quote(edition),  # 版本文本
        'cblCategory': urllib.parse.quote(cblCategory),  # 中图法分类号
        'presentId': presentId,  # 附赠默认id 无-0
        'present': present,  # 附赠文本 默认 无
        'presentNum': presentNum,  # 附赠数量，有则必填
        'modelAttrStr': urllib.parse.quote(modelAttrStr),
        # 作者国别/地区/朝代ID: value; 原版书名: value 例如：1000496:宋朝;1000619:原版书名;
        'commonAttrStr': commonAttrStr,  # 1000732:1_7_19;1000714:1; 选多个用下划线隔开
        'volumeName': urllib.parse.quote(volumeName),  # 分册名
        'volumeNumber': urllib.parse.quote(volumeNumber),  # 分册号
        'reignTitle': reignTitle,  # 年号
        # 前面的版本填过了，不用再填了
        'cipNumber': cipNumber,  # cip数据编号 案例，冒号隔开: 1111:222222
        'editor': urllib.parse.quote(editor),  # 编者
        'translator': urllib.parse.quote(translator),  # 译者
        'painter': urllib.parse.quote(painter),  # 绘者
        'publishingBrands': urllib.parse.quote(publishingBrands),  # 出版品牌
        'barcodeImg': barcodeImg,  # 条码图片url完整地址
        'productsCopyrightImage': productsCopyrightImage,  # 版权页图片url完整地址
        'imageUrlList': imageUrlList,  # 主图 至少一张 800X800
        'marketingImgUrl': marketingImgUrl,  # 营销素材图 800X800 先不传
        'videoInfo': str(videoInfo),  # 视频 先不传
        'itemFeatures': urllib.parse.quote(itemFeatures),  # 产品特色(产品详情)
        'editRecommend': urllib.parse.quote(editRecommend),  # 编辑推荐(产品详情)
        'contentRecommend': urllib.parse.quote(contentRecommend),  # 内容简介(产品详情)
        'authorItro': urllib.parse.quote(authorItro),  # 作者简介(产品详情)
        'mediaComment': urllib.parse.quote(mediaComment),  # 媒体评论(产品详情)
        'catelog': urllib.parse.quote(catelog),  # 目录(产品详情)
        'preface': urllib.parse.quote(preface),  # 前言(产品详情)
        'wonderfulDigest': urllib.parse.quote(wonderfulDigest),  # 免费在线读(产品详情)
        'illustration': urllib.parse.quote(illustration),  # 书摘与插画(产品详情)
        'itemMobileDetail': urllib.parse.quote(itemMobileDetail),  # 手机端描述(产品详情)
        'editRecommendIndex': editRecommendIndex,  # 编辑推荐索引默认传
        'contentRecommendIndex': contentRecommendIndex,  # 内容简介索引默认传
        'authorItroIndex': authorItroIndex,  # 作者简介索引默认传
        'mediaCommentIndex': mediaCommentIndex,  # 媒体评论索引默认传
        'catelogIndex': catelogIndex,  # 目录推荐索引默认传
        'prefaceIndex': prefaceIndex,  # 前言索引默认传
        'wonderfulDigestIndex': wonderfulDigestIndex,  # 免费在线读索引默认传
        'illustrationIndex': illustrationIndex,  # 书摘与插画索引默认传
        'readChapter': urllib.parse.quote(readChapter),  # 抢先读
        # 下边的都不知道是什么
        'itemCategoryId': itemCategoryId,
        'itemSubcategoryId1': itemSubcategoryId1,
        'itemSubcategoryId2': itemSubcategoryId2,
        'originalBookName': originalBookName,
        'salePrice': salePrice,
        'stockPrice': stockPrice,
        'isShopVip': isShopVip,
        'status': status,
        'isCod': isCod,
        'columnDescListId': columnDescListId,
        'columnSortNum': columnSortNum,
        'seriesName': seriesName,
    }
    response = requests.post('https://vrmpimsup.dangdang.com/vrmpimsup/itembook/modify', cookies=cookies, headers={
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    }, data=params)
    json_data = json.loads(response.text)
    if "result" in json_data and json_data['result'] == True:
        return {"code": 200, "message": "操作成功", "reason": json_data}
    else:
        return {"code": 0, "message": "操作失败", "reason": json_data}
